package com.luntan.school.service.impl;

import com.luntan.school.dao.CommentDao;
import com.luntan.school.model.Comment;
import com.luntan.school.service.CommentService;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ConmmentServiceImpl implements CommentService {

    private CommentDao commentDao = (CommentDao) new ConmmentServiceImpl();
    @Override
    public void addComment(Comment comment) {
        commentDao.addComment(comment);
    }

    @Override
    public List<Comment> getAllCommentsByPostsId(int postsId) {
        List<Comment> comments = commentDao.getCommentsByPostsId(postsId);

        //处理数据
        //保存数据，方便查询，去重 ，使用ConcurrentHashMap是为了解决线程安全问题，
        // 防止引发ConcurrentModificationException
        Map<Long,Comment> commentMap = new ConcurrentHashMap<>();
        for (Comment comment:comments) {
            commentMap.put(comment.getId(),comment);
        }

        //处理所有关联
        for (Comment comment:comments) {
            if (comment.getReplyId() > 0) {
                List<Comment> replyComments = commentMap.get(comment.getId()).getReplies();
                if (replyComments == null) {
                    replyComments = new ArrayList<>();
                    //存入MAP
                    commentMap.get(comment.getId()).setReplies(replyComments);
                }
                replyComments.add(commentMap.get(comment.getReplyId()));// 加入到回复列表中
            }
        }

        //移除回复的评论（保留评价）

        for (Long id:commentMap.keySet()) {
            Comment comment = commentMap.get(id);
            if (comment.getReplyFor().getId() > 0){
                commentMap.remove(comment.getId());
            }
        }

        //生成最终结果数据
        List<Comment> comments1 = new ArrayList<>();
        for (Long id:commentMap.keySet()){
            comments1.add(commentMap.get(id));
        }
        return comments1;
    }

    @Override
    public int updateLikeNum(int commentId, boolean likeNum) {
        return commentDao.updateLikeNum(commentId,likeNum);
    }

    @Override
    public int updateDislikeNum(int commentID, boolean dislike) {
        return commentDao.updateDislikeNum(commentID,dislike);
    }

    @Override
    public boolean deleteComment(long commentId) {
        this.commentDao.hiddenComment(commentId,true);
        return true;
    }


    @Override
    public boolean recoverComment(long commentId) {
        this.commentDao.hiddenComment(commentId,false);
        return true;
    }
}
